package com.ittest.service.impl;

import com.ittest.dao.RoleDao;
import com.ittest.dao.UserDao;
import com.ittest.domain.Role;
import com.ittest.domain.User;
import com.ittest.service.UserService;
import org.springframework.dao.EmptyResultDataAccessException;

import java.util.List;

public class UserServiceImpl implements UserService {

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    private UserDao userDao;

    private RoleDao roleDao;

    public void setRoleDao(RoleDao roleDao) {
        this.roleDao = roleDao;
    }

    @Override
    public List<User> list() {
        List<User> userList = userDao.findAll();
        //封装userList中的每一个rores数据
        for (User user:userList) {
            //获得user的id
            Long id = user.getId();
            //将id作为参数 查询当前userID对应的role集合
            List<Role> roles = roleDao.findRoleByUserId(id);
            user.setRoles(roles);
        }

        return userList;
    }

    @Override
    public void save(User user, Long[] roleIds) {
        //1.第一步，想sys_user表中存储数据
        Long userId = userDao.save(user);
        //2.第二部，想sys_user_role关系表中存储多条数据
        userDao.saveUserRoleRel(userId,roleIds);
    }

    @Override
    public void del(Long userId) {
        //1.删除关系表sys_user_role
        userDao.delUserRoleRel(userId);
        //2.删除sys_user表
        userDao.del(userId);
    }

    @Override
    public User login(String username, String password) {
        try {
            User user = userDao.findUsernameAndPassword(username, password);
            return user;
        }catch (EmptyResultDataAccessException e){
            return null;
        }
    }
}
